using System;
using System.Collections.Generic;
using UnityEngine;

public class LoadNextLevel : MonoBehaviour
{
    private bool load;
    private string nextLevel = "";

    private void Start()
    {
        EventManager.OnLevelSelected += EventManagerOnLevelSelected;
        EventManager.OnInput += EventManagerOnInput;
    }

    private void Update()
    {
        if (!string.IsNullOrEmpty(nextLevel))
            if (ValidLevel() && this.load || ValidLevel() && this.nextLevel == "Map")
                Application.LoadLevel(this.nextLevel);
    }

    private void OnDestroy()
    {
        EventManager.OnInput -= EventManagerOnInput;
        EventManager.OnLevelSelected -= EventManagerOnLevelSelected;
    }

    private void EventManagerOnInput(object sender, List<InputEventArgs> inputEventArgses)
    {
        foreach (InputEventArgs inputEventArgs in inputEventArgses)
        {
            switch (inputEventArgs.Input)
            {
                case "Return":
                    this.load = ValidLevel();
                    break;
                case "A":
                    if (inputEventArgs.Device == InputDevice.XboxController && ValidLevel())
                        this.load = true;
                    else
                        this.load = false;
                    break;
            }
        }
    }

    private void EventManagerOnLevelSelected(object sender, ChangedLevelEventArgs changedLevelEventArgs)
    {
        this.nextLevel = changedLevelEventArgs.nextLevel;
    }

    private bool ValidLevel()
    {
        string tempNextLevel = this.nextLevel.Contains("Level") ? this.nextLevel.Replace("Level", "") : this.nextLevel;
        return AllLevels.Levels.Contains(tempNextLevel);
    }
}